import React, { Component } from 'react'
import { Button, Icon, Input, DatePicker, Popover, Table } from 'antd';
import '@/assets/css/settings';
import * as APIService from '../../../axios/api_yq'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { getFirstDayOfTheMonth, getNowDate, getLastDayOfTheMonth, getDayAll, getMonthAll, getTime, getDateByString, getStringByDate, getDateYYYYMM } from '../../../utils/action';
import moment from 'moment'
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

export default class GanttPicture extends Component {
    state = {
        dataSource: [],
        nowDateTime: getTime(),
        loading: false,
        searchItem: {
            // 本月第一天
            startTime: getFirstDayOfTheMonth(),
            // 当前时间
            endTime: getNowDate(),
        },
        stateList: [
            { id: 0, color: '#3cdaa1', colorSize: '#00c77f' },
            { id: 1, color: '#3dacf1', colorSize: '#007fdb' },
            { id: 2, color: '#f77567', colorSize: '#e43d23' },
            { id: 3, color: '#b158ff', colorSize: '#8e00c6' },
            { id: 4, color: '#ffc960', colorSize: '#f9a400' },
            { id: 5, color: '#dd75ff', colorSize: '#cc0dde' },
            { id: 6, color: '#ffb875', colorSize: '#f07816' },
        ],
        paging: {},
        columns: [],
        activeKey: '0',
    };
    UNSAFE_componentWillMount() {
        this.fetch()
    }
    //初始化加载数据
    fetch = (pageNum = 1, pageSize = 10) => {
        const { values } = this.state
        this.setState({
            loading: true,
            paging: { pageNum: pageNum, pageSize: pageSize }
        })
        let a = { pageNum: pageNum, pageSize: pageSize }
        this.search({ ...values, ...a })
    }
    // 查询接口
    search = (value, paging) => {
        // console.log(value, paging);
        APIService.ganttChart({ ...value, ...paging }).then((item) => {
            // console.log('查询数据', item);
            if (item.data.code === 200) {
                this.getColumns(item.data.data.data)
                this.setState({
                    loading: false,
                    paging: {
                        pageNum: item.data.data.pageNum,
                        pageSize: item.data.data.pageSize,
                        total: item.data.data.total,
                    }
                })
                return
            }
            openModalMessage('error', item.data.msg)

        })
    }
    getColumns = (data) => {
        //        总数据     获取最小开始日期                            结束日期    最小一组      
        let dataSource = [...data], startTime = '', endTime1 = [], endTime = '', startMin = []
        for (let item1 of data) {
            let date = [
                item1.dataOutputTime !== null ? getTime(item1.dataOutputTime) : this.state.nowDateTime,
                item1.assembleStartTime !== null ? getTime(item1.assembleStartTime) : this.state.nowDateTime,
                item1.firstDeliveryTime !== null ? getTime(item1.firstDeliveryTime) : this.state.nowDateTime,
                item1.endTime !== null ? getTime(item1.endTime) : this.state.nowDateTime,
                item1.firstOutputTime !== null ? getTime(item1.firstOutputTime) : this.state.nowDateTime
            ]
            // 最小值
            var min = date[0]
            for (var i = 0; i < date.length; i++) {
                if (date[i] < min) {
                    min = date[i]
                }
            }
            startMin.push(min)
            // 最大值
            var max = date[0]
            for (var i = 0; i < date.length; i++) {
                if (date[i] > max) {
                    max = date[i]
                }
            }
            endTime1.push(max)
        }
        // 排序小到大
        startMin.sort((a, b) => {
            return a - b
        })
        startTime = startMin[0]
        // 大到小
        endTime1.sort((a, b) => {
            return b - a
        })
        endTime = endTime1[0] - this.state.nowDateTime > 0 ? endTime1[0] : this.state.nowDateTime
        // 月份          两个月份之间  总数
        let month = [], date = [], dateAll = []
        // 开始时间的月份
        let startMonth = new Date(startTime).getMonth() + 1
        // 当前的月份
        let endMonth = new Date(endTime).getMonth() + 1
        if (startMonth == endMonth) {
            month = [startMonth]
            // 两个日期之前的时间
            date = [getDayAll(startTime, endTime)]
            dateAll = [...getDayAll(startTime, endTime)]
            // console.log('两个日期之间的时间', date);
        } else {
            // 两个日期之间的月份
            month = getMonthAll(startTime, endTime)
            // 本月最后一天 getLastDayOfTheMonth  getDayAll两个日期之间的时间
            date = [getDayAll(startTime, getTime(getLastDayOfTheMonth(startTime))), getDayAll(getTime(getFirstDayOfTheMonth(endTime)), this.state.nowDateTime)]
            // 本月最后一天
            dateAll = [...getDayAll(startTime, getTime(getLastDayOfTheMonth(startTime))), ...getDayAll(getTime(getFirstDayOfTheMonth(endTime)), this.state.nowDateTime)]
        }
        // 表头的月份和天数
        let children = []
        for (let i in month) {
            let dateChildren = []
            for (let da of date[i]) {
                let obj1 = {
                    title: Number(da.split('-')[2]),
                    dataIndex: da,
                    key: da,
                    width: 50,
                    align: 'center'
                }
                dateChildren.push(obj1)
            }

            let obj = {
                title: month[i] + ' 月',
                children: dateChildren,
                editable: true,
            }
            children.push(obj)
        }
        let minDate = '', maxDate = ''
        let columns = [
            {
                title: '计划',
                width: 160,
                children: [
                    {
                        title: '月份',
                        width: 160,
                        children: [
                            {
                                title: '批号',
                                dataIndex: 'model',
                                key: 'model',
                                width: 160,
                                sorter: (a, b) => compareString(a.batchNo, b.batchNo),
                            },
                        ],
                    },
                ],
            },
            // 这里引入
            {
                title: '月计划',
                children,
            },
            {
                title: '',
                render: (text, record, index) => {
                    let a = this.state.stateList.find(item => item.id == record.color)
                    // 最大
                    let dateArr = [
                        record.dataOutputTime !== null ? getTime(record.dataOutputTime) : this.state.nowDateTime,
                        record.assembleStartTime !== null ? getTime(record.assembleStartTime) : this.state.nowDateTime,
                        record.firstDeliveryTime !== null ? getTime(record.firstDeliveryTime) : this.state.nowDateTime,
                        record.endTime !== null ? getTime(record.endTime) : this.state.nowDateTime,
                        record.firstOutputTime !== null ? getTime(record.firstOutputTime) : this.state.nowDateTime
                    ]
                    // 最大
                    let dateArr1 = [
                        record.dataOutputTime ? getTime(record.dataOutputTime) : null,
                        record.dataOutputTime ? getTime(record.dataOutputTime) : null,
                        record.firstDeliveryTime ? getTime(record.firstDeliveryTime) : null,
                        record.endTime ? getTime(record.endTime) : null,
                        record.firstOutputTime ? getTime(record.firstOutputTime) : null
                    ]
                    // 最小值
                    var min = dateArr[0]
                    for (var i = 0; i < dateArr.length; i++) {
                        if (dateArr[i] < min) {
                            min = dateArr[i]
                        }
                    }
                    minDate = min
                    // 最大值
                    var max = dateArr1[0]
                    for (var i = 0; i < dateArr1.length; i++) {
                        if (dateArr1[i] > max) {
                            max = dateArr1[i]
                        }
                    }
                    maxDate = max
                    // 最小
                    let vstart = getStringByDate(minDate) ? getStringByDate(minDate).split(' 00:')[0] : this.state.nowDate
                    // 最大
                    let vend = getStringByDate(maxDate) ? getStringByDate(maxDate).split(' 00:')[0] : this.state.nowDate
                    let startIndex = dateAll.indexOf(vstart)
                    let endIndex = dateAll.indexOf(vend)
                    let top = 165 + 54 * index
                    let left = 160 + startIndex * 50
                    let width = (endIndex - startIndex + 1) * 50
                    let content = (
                        <div style={{ fontWeight: 'bold' }}>
                            <p>月计划</p>
                            <p>
                                <span>机型：{record.model}</span><br />
                                <span>资料输出时间：{record.dataOutputTime ? record.dataOutputTime.split(' 00:')[0] : '--'}</span><br />
                                <span>装配开始时间：{record.assembleStartTime ? record.assembleStartTime.split(' 00:')[0] : '--'}</span><br />
                                <span>第一交机时间：{record.firstDeliveryTime ? record.firstDeliveryTime.split(' 00:')[0] : '--'}</span><br />
                                <span>试机结束时间：{record.endTime ? record.endTime.split(' 00:')[0] : '--'}</span><br />
                                <span>第一出机时间：{record.firstOutputTime ? record.firstOutputTime.split(' 00:')[0] : '--'}</span><br />
                            </p>
                        </div>
                    )
                    let style = {
                        position: 'absolute',
                        left: (dateAll.indexOf(getStringByDate(record.dataOutputTime).split(' 00:')[0]) - startIndex) * 50,
                        height: '50px',
                        width: '50px',
                        backgroundColor: a ? a.colorSize : '#007fdb'
                    }
                    let style1 = {
                        position: 'absolute',
                        left: (dateAll.indexOf(getStringByDate(record.assembleStartTime).split(' 00:')[0]) - startIndex) * 50,
                        height: '50px',
                        width: '50px',
                        backgroundColor: a ? a.colorSize : '#007fdb'
                    }
                    let style2 = {
                        position: 'absolute',
                        left: (dateAll.indexOf(getStringByDate(record.firstDeliveryTime).split(' 00:')[0]) - startIndex) * 50,
                        height: '50px',
                        width: '50px',
                        backgroundColor: a ? a.colorSize : '#007fdb'
                    }
                    let style3 = {
                        position: 'absolute',
                        left: (dateAll.indexOf(getStringByDate(record.endTime).split(' 00:')[0]) - startIndex) * 50,
                        height: '50px',
                        width: '50px',
                        backgroundColor: a ? a.colorSize : '#007fdb'
                    }
                    let style4 = {
                        position: 'absolute',
                        left: (dateAll.indexOf(getStringByDate(record.firstOutputTime).split(' 00:')[0]) - startIndex) * 50,
                        height: '50px',
                        width: '50px',
                        backgroundColor: a ? a.colorSize : '#007fdb'
                    }
                    return <Popover
                        content={content}
                        title={false}
                        trigger="click"   // hover | click | focus
                        mouseLeaveDelay={0}
                    >
                        <div
                            style={{
                                position: 'absolute', left: left, top: top, backgroundColor: a ? a.color : '#3dacf1',
                                width: width, height: 50, lineHeight: '50px', textOverflow: 'ellipsis',
                                overflow: 'hidden', whiteSpace: 'nowrap',
                            }}
                            onClick={() => this.showDetails(record)}
                            title={record.procedureCode}
                        >
                            {/* textAlign: 'center', */}
                            <div style={{ position: 'relative', textAlign: 'center', fontSize: '16px', fontWeight: 'bold', color: '#fff' }}>
                                {
                                    record.dataOutputTime !== null ? <div style={style} title={'资料输出时间'}>
                                        资
                                    </div> : null
                                }
                                {
                                    record.assembleStartTime !== null ? <div style={style1} title={'装配开始时间'}>
                                        装
                                    </div> : null
                                }
                                {
                                    record.firstDeliveryTime !== null ? <div style={style2} title={'第一交机时间'}>
                                        交
                                    </div> : null
                                }
                                {
                                    record.endTime !== null ? <div style={style3} title={'试机结束时间'}>
                                        试
                                    </div> : null
                                }
                                {
                                    record.firstOutputTime !== null ? <div style={style4} title={'第一出机时间'}>
                                        出
                                    </div> : null
                                }
                            </div>
                        </div>
                    </Popover>
                }
            },
        ]
        this.setState({ dataSource, columns })
    }
    // 点击后拿到的数据
    showDetails = (record) => {
        // console.log(record, 'record这是什么');
    }
    downloadFather = (value) => {
        const { paging } = this.state
        let month = value ? { month: getDateYYYYMM(value._d) } : null
        this.search(month, paging)
        console.log(getDateYYYYMM(value._d));
    }
    render() {
        const { paging, loading, dataSource, searchItem, downloadLoading, columns } = this.state;
        return (
            <div>
                <BasicLayout
                    name='月计划-甘特图' icon="table"
                    buttons={[
                        <MonthPicker key={2} onChange={this.downloadFather} placeholder="请选择月份" defaultValue={dataSource ? dataSource.month : null} />
                    ]}
                >
                    <Table
                        style={{ position: 'relative', overflow: 'auto' }}
                        columns={columns}
                        dataSource={dataSource}
                        rowKey={(record, index) => record.id}
                        bordered
                        pagination={false}
                        loading={loading}
                    >
                    </Table>
                    <BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
                </BasicLayout>
            </div>
        )
    }
}
